<template>
  <div class="p-6">
    <el-card class="rounded-xl mb-6" shadow="hover">
      <template #header>
        <div class="flex items-center">
          <el-icon>
            <Search></Search>
          </el-icon>
          <span class="ml-2 font-bold text-lg">收货地址查询</span>
        </div>
      </template>
      <el-form :model="searchForm" label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="收件人">
              <el-input v-model="searchForm.recipient" clearable placeholder="请输入收件人"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号">
              <el-input v-model="searchForm.phone" clearable placeholder="请输入手机号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="详细地址">
              <el-input v-model="searchForm.address" clearable placeholder="请输入详细地址"/>
            </el-form-item>
          </el-col>
          <el-col :span="4" style="text-align: right;">
            <el-button :icon="ElIconSearch" type="primary" @click="handleSearch">查询</el-button>
            <el-button :icon="ElIconRefreshRight" @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="rounded-xl" shadow="hover">
      <template #header>
        <div class="flex justify-between items-center">
          <div class="flex items-center">
            <el-icon>
              <Tickets/>
            </el-icon>
            <span class="ml-2 font-bold text-lg">我的收货地址</span>
          </div>
          <el-button :icon="ElIconPlus" type="primary" @click="handleOpenAddDialog">新增地址</el-button>
        </div>
      </template>

      <div v-loading="loading" class="min-h-[200px]">
        <template v-if="addressList.length > 0">
          <el-row :gutter="20">
            <el-col v-for="address in addressList" :key="address.id" :span="8" class="mb-4">
              <el-card class="rounded-lg h-full flex flex-col justify-between" shadow="hover">
                <div>
                  <div class="flex items-center mb-2">
                    <el-icon>
                      <User/>
                    </el-icon>
                    <span class="font-semibold ml-2 text-lg">{{ address.recipient }}</span>
                    <el-tag v-if="address.isDefault === 1" class="ml-auto rounded-full" size="small" type="success">
                      默认
                    </el-tag>
                  </div>
                  <div class="flex items-center mb-2 text-gray-600">
                    <el-icon>
                      <Phone></Phone>
                    </el-icon>
                    <span class="ml-2">{{ address.phone }}</span>
                  </div>
                  <div class="flex items-start text-gray-700">
                    <el-icon>
                      <Location></Location>
                    </el-icon>
                    <span class="ml-2 break-all">{{ address.address }}</span>
                  </div>
                  <div class="text-xs text-gray-400 mt-2 text-right">创建时间: {{ address.createTime }}</div>
                </div>
                <div class="mt-4 text-right">
                  <el-button :icon="ElIconEdit" size="small" @click="handleOpenEditDialog(address)">编辑</el-button>
                  <el-button :icon="ElIconDelete" size="small" type="danger" @click="handleDeleteAddress(address.id)">
                    删除
                  </el-button>
                  <el-button v-if="address.isDefault !== 1" :icon="ElIconStar" size="small" type="warning"
                             @click="handleSetDefault(address)">设为默认
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <el-pagination
              :current-page="pagination.page"
              :page-size="pagination.size"
              :page-sizes="[10, 20, 50, 100]"
              :total="pagination.total"
              background
              class="justify-end"
              layout="total, sizes, prev, pager, next, jumper"
              style="margin-top: 10px"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
          />
        </template>
        <el-empty v-else class="py-10" description="暂无收货地址"/>
      </div>
    </el-card>

    <!-- 新增/编辑地址弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        :close-on-click-modal="false"
        :title="dialogTitle"
        class="rounded-lg"
        width="500px"
    >
      <el-form
          ref="addressFormRef"
          :model="currentAddress"
          :rules="rules"
          label-position="left"
          label-width="100px"
      >
        <el-form-item label="收件人" prop="recipient">
          <el-input v-model="currentAddress.recipient" placeholder="请输入收件人"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="currentAddress.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
              v-model="currentAddress.address"
              :rows="3"
              placeholder="请输入详细地址"
              type="textarea"
          />
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch
              v-model="currentAddress.isDefault"
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitAddress(addressFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  Delete as ElIconDelete,
  Edit as ElIconEdit,
  Location,
  Phone,
  Plus as ElIconPlus,
  RefreshRight as ElIconRefreshRight,
  Search,
  Search as ElIconSearch,
  Star as ElIconStar,
  Tickets,
  User,
} from '@element-plus/icons-vue' // 引入ElementPlus Icon
import request from '@/utils/request' // 假设您有这个request工具

// --- 状态定义 ---
const searchForm = reactive({
  recipient: '',
  phone: '',
  address: ''
})

const addressList = ref([]) // 收货地址列表
const loading = ref(false) // 加载状态
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const dialogVisible = ref(false) // 弹窗显示状态
const dialogTitle = ref('') // 弹窗标题
const currentAddress = reactive({ // 当前编辑/新增的地址对象
  id: null,
  recipient: '',
  phone: '',
  address: '',
  isDefault: 0 // 默认非默认
})
const addressFormRef = ref(null) // 表单ref，用于校验

// 表单校验规则
const rules = reactive({
  recipient: [
    {required: true, message: '请输入收件人', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
  ],
  address: [
    {required: true, message: '请输入详细地址', trigger: 'blur'},
    {min: 5, max: 255, message: '长度在 5 到 255 个字符', trigger: 'blur'}
  ]
})

// --- 生命周期钩子 ---
onMounted(() => {
  handleSearch() // 页面加载时查询一次数据
})

// --- 事件处理函数 ---

// 页码改变
const handlePageChange = (newPage) => {
  pagination.page = newPage
  handleSearch()
}

// 每页数量改变
const handleSizeChange = (newSize) => {
  pagination.size = newSize
  pagination.page = 1 // 切换每页数量后回到第一页
  handleSearch()
}

// 查询收货地址列表
const handleSearch = async () => {
  loading.value = true
  try {
    const payload = {
      page: pagination.page,
      size: pagination.size,
      param: searchForm,
      orders: [
        {column: 'createTime', asc: false} // 默认按创建时间降序
      ]
    }
    const result = await request.post('/userAddress/page', payload)
    addressList.value = result.records
    pagination.total = result.total
  } catch (error) {
    // 实际项目中会进行错误处理，这里按要求不加try-catch和code判断
    console.error('获取地址列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置查询条件
const handleReset = () => {
  searchForm.recipient = ''
  searchForm.phone = ''
  searchForm.address = ''
  pagination.page = 1
  handleSearch()
}

// 打开新增地址弹窗
const handleOpenAddDialog = () => {
  dialogTitle.value = '新增收货地址'
  // 重置currentAddress
  Object.assign(currentAddress, {
    id: null,
    recipient: '',
    phone: '',
    address: '',
    isDefault: 0
  })
  dialogVisible.value = true
}

// 打开编辑地址弹窗
const handleOpenEditDialog = (address) => {
  dialogTitle.value = '编辑收货地址'
  Object.assign(currentAddress, JSON.parse(JSON.stringify(address))) // 深拷贝，避免直接修改列表数据
  dialogVisible.value = true
}

// 提交新增/编辑地址
const handleSubmitAddress = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        if (currentAddress.id) {
          // 编辑
          await request.put('/userAddress', currentAddress)
          ElMessage.success('地址修改成功！')
        } else {
          // 新增
          await request.post('/userAddress', currentAddress)
          ElMessage.success('地址新增成功！')
        }
        dialogVisible.value = false // 关闭弹窗
        await handleSearch() // 刷新列表
      } catch (error) {
        console.error('提交地址失败:', error)
        // 实际项目中会进行错误处理，这里按要求不加try-catch和code判断
        ElMessage.error('提交地址失败，请稍后再试！')
      }
    } else {
      ElMessage.error('请检查表单填写是否完整！')
      return false
    }
  })
}

// 删除地址
const handleDeleteAddress = async (id) => {
  ElMessageBox.confirm(
      '此操作将永久删除该地址, 是否继续?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        roundButton: true,
      }
  )
      .then(async () => {
        await request.delete('/userAddress/' + id) // DELETE请求将ID放入data中
        ElMessage.success('删除成功！')
        await handleSearch() // 刷新列表
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
}

// 设为默认地址
const handleSetDefault = async (address) => {
  try {
    // 假设后端会处理将其他地址设为非默认的逻辑
    await request.post('/userAddress/setCurrent/' + address.id)
    ElMessage.success('已设为默认地址！')
    await handleSearch() // 刷新列表
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置默认地址失败，请稍后再试！')
  }
}
</script>

<style scoped>
.p-6 {
  padding: 1.5rem;
}

.mb-6 {
  margin-bottom: 1.5rem;
}

:deep(.el-card),
:deep(.el-input),
:deep(.el-button),
:deep(.el-dialog),
:deep(.el-message-box) {
  border-radius: 8px !important; /* Tailwind rounded-lg */
}

/* 弹窗底部按钮对齐 */
.dialog-footer {
  text-align: center;
}
</style>